/*
 * PastaView.java
 */

package pasta;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;

/**
 * The application's main frame.
 */
public class PastaView extends FrameView {

    public PastaView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAddFileBox() {
        if (addFileBox == null) {
            JFrame mainFrame = PastaApp.getApplication().getMainFrame();
            addFileBox = new PastaAddFileBox(mainFrame);
            addFileBox.setLocationRelativeTo(mainFrame);
        }
        PastaApp.getApplication().show(addFileBox);
    }


    @Action
    public void showConnectBox() {
        if (connectBox == null) {
            JFrame mainFrame = PastaApp.getApplication().getMainFrame();
            connectBox = new PastaConnectBox(mainFrame);
            connectBox.setLocationRelativeTo(mainFrame);
        }
        PastaApp.getApplication().show(connectBox);
    }

    @Action
    public void showSearchFileBox() {
        if (searchFileBox == null) {
            JFrame mainFrame = PastaApp.getApplication().getMainFrame();
            searchFileBox = new PastaSearchFileBox(mainFrame);
            searchFileBox.setLocationRelativeTo(mainFrame);
        }
        PastaApp.getApplication().show(searchFileBox);
        
    }

    /*
    @Action
    public void displaySearchedFileItens(ArrayList<Music> searchResultSet) {
        DefaultTableModel tblModel = (DefaultTableModel)this.jTable1.getModel();
        Iterator it = searchResultSet.iterator();
        while(it.hasNext()) {
                final Music music = (Music)it.next();
                tblModel.addRow(new Object[]{music});
        }
    }
     * 
     */


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        searchTextField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        downloadButton = new javax.swing.JButton();
        myFilesButton = new javax.swing.JButton();
        searchFilesButton = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        PastaMenu = new javax.swing.JMenu();
        connectMenuItem = new javax.swing.JMenuItem();
        updateCatalogMenuItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        javax.swing.JMenuItem quitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem addFileMenuItem = new javax.swing.JMenuItem();
        searchFileMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(pasta.PastaApp.class).getContext().getResourceMap(PastaView.class);
        searchTextField.setText(resourceMap.getString("searchTextField.text")); // NOI18N
        searchTextField.setName("searchTextField"); // NOI18N
        searchTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchTextFieldActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] {}, new String [] {"Name", "Artist","Album","Gender"}));
        jTable1.setColumnSelectionAllowed(true);
        jTable1.setName("jTable1"); // NOI18N
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(pasta.PastaApp.class).getContext().getActionMap(PastaView.class, this);
        downloadButton.setAction(actionMap.get("downloadSelectedFiles")); // NOI18N
        downloadButton.setText(resourceMap.getString("downloadButton.text")); // NOI18N
        downloadButton.setName("downloadButton"); // NOI18N

        myFilesButton.setAction(actionMap.get("showMyDownloadedFiles")); // NOI18N
        myFilesButton.setText(resourceMap.getString("myFilesButton.text")); // NOI18N
        myFilesButton.setName("myFilesButton"); // NOI18N

        searchFilesButton.setAction(actionMap.get("showPreviousSearchResults")); // NOI18N
        searchFilesButton.setText(resourceMap.getString("searchFilesButton.text")); // NOI18N
        searchFilesButton.setName("searchFilesButton"); // NOI18N

        org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(mainPanelLayout.createSequentialGroup()
                        .addContainerGap(486, Short.MAX_VALUE)
                        .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, searchTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 134, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, downloadButton)))
                    .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, myFilesButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, searchFilesButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE)))
                .addContainerGap())
            .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, mainPanelLayout.createSequentialGroup()
                    .addContainerGap(152, Short.MAX_VALUE)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 468, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap()))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(searchTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(19, 19, 19)
                .add(searchFilesButton)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(myFilesButton)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 234, Short.MAX_VALUE)
                .add(downloadButton)
                .add(8, 8, 8))
            .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, mainPanelLayout.createSequentialGroup()
                    .addContainerGap(56, Short.MAX_VALUE)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 290, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(54, 54, 54)))
        );

        menuBar.setName("menuBar"); // NOI18N

        PastaMenu.setText(resourceMap.getString("PastaMenu.text")); // NOI18N
        PastaMenu.setName("PastaMenu"); // NOI18N

        connectMenuItem.setAction(actionMap.get("showConnectBox")); // NOI18N
        connectMenuItem.setText(resourceMap.getString("connectMenuItem.text")); // NOI18N
        connectMenuItem.setName("connectMenuItem"); // NOI18N
        PastaMenu.add(connectMenuItem);

        updateCatalogMenuItem.setAction(actionMap.get("updateCatalog")); // NOI18N
        updateCatalogMenuItem.setText(resourceMap.getString("updateCatalogMenuItem.text")); // NOI18N
        updateCatalogMenuItem.setName("updateCatalogMenuItem"); // NOI18N
        PastaMenu.add(updateCatalogMenuItem);

        jSeparator1.setName("jSeparator1"); // NOI18N
        PastaMenu.add(jSeparator1);

        quitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        quitMenuItem.setText(resourceMap.getString("quitMenuItem.text")); // NOI18N
        quitMenuItem.setName("quitMenuItem"); // NOI18N
        PastaMenu.add(quitMenuItem);

        menuBar.add(PastaMenu);

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        addFileMenuItem.setAction(actionMap.get("showAddFileBox")); // NOI18N
        addFileMenuItem.setText(resourceMap.getString("addFileMenuItem.text")); // NOI18N
        addFileMenuItem.setName("addFileMenuItem"); // NOI18N
        addFileMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addFileMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(addFileMenuItem);

        searchFileMenuItem.setAction(actionMap.get("showSearchFileBox")); // NOI18N
        searchFileMenuItem.setText(resourceMap.getString("searchFileMenuItem.text")); // NOI18N
        searchFileMenuItem.setName("searchFileMenuItem"); // NOI18N
        fileMenu.add(searchFileMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N
        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 640, Short.MAX_VALUE)
            .add(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(statusMessageLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 444, Short.MAX_VALUE)
                .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelLayout.createSequentialGroup()
                .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(statusMessageLabel)
                    .add(statusAnimationLabel)
                    .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void addFileMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addFileMenuItemActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_addFileMenuItemActionPerformed

    private void searchTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchTextFieldActionPerformed
        // TODO add your handling code here:
        cleanTable();
        ArrayList<Music> searchResultSet = new ArrayList<Music> ();
        try {
            String keyWord = searchTextField.getText();
            searchResultSet = PastaApp.getApplication().getPastApp().searchDataIntoPast(keyWord);
            
            DefaultTableModel tblModel = (DefaultTableModel)this.jTable1.getModel();
            Iterator it = searchResultSet.iterator();
            while(it.hasNext()) {
                final Music music = (Music)it.next();
                System.out.println(music);
                tblModel.addRow(music.print());
            }

        } catch (Exception e){
            System.out.println("Error Searching Music");
        }
    }//GEN-LAST:event_searchTextFieldActionPerformed

    @Action
    public void updateCatalog() {
        PastaApp.getApplication().getPastApp().retrieveCatalogFromPast();
    }

    private void cleanTable() {
      jTable1.setModel(new javax.swing.table.DefaultTableModel(new Object [][] {}, new String [] {"Name", "Artist","Album","Gender"}) {
            boolean[] canEdit = new boolean [] { false };

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
    }

    @Action
    public void downloadSelectedFiles() throws IOException {
        int[] selectedFiles = jTable1.getSelectedRows();
        try {
            PastaApp.getApplication().getPastApp().retrieveMusicsFromPast(selectedFiles);
        } catch (InterruptedException ex) {
            Logger.getLogger(PastaView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Action
    public void showPreviousSearchResults() {
        cleanTable();
        ArrayList<Music> searchResultSet = new ArrayList<Music> ();
        try {
            //String keyWord = searchTextField.getText();
            searchResultSet = PastaApp.getApplication().getPastApp().getSearchResultArray();

            DefaultTableModel tblModel = (DefaultTableModel)this.jTable1.getModel();
            Iterator it = searchResultSet.iterator();
            while(it.hasNext()) {
                final Music music = (Music)it.next();
                System.out.println(music);
                tblModel.addRow(music.print());
            }

        } catch (Exception e){
            System.out.println("Error Searching Music");
        }
    }

    @Action
    public void showMyDownloadedFiles() {
        cleanTable();
        ArrayList<Music> searchResultSet = new ArrayList<Music> ();
        try {
            //String keyWord = searchTextField.getText();
            searchResultSet = PastaApp.getApplication().getPastApp().getMyDownloadedFiles();

            DefaultTableModel tblModel = (DefaultTableModel)this.jTable1.getModel();
            Iterator it = searchResultSet.iterator();
            while(it.hasNext()) {
                final Music music = (Music)it.next();
                System.out.println(music);
                tblModel.addRow(music.print());
            }

        } catch (Exception e){
            System.out.println("Error Searching Music");
        }
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu PastaMenu;
    private javax.swing.JMenuItem connectMenuItem;
    private javax.swing.JButton downloadButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JButton myFilesButton;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JMenuItem searchFileMenuItem;
    private javax.swing.JButton searchFilesButton;
    private javax.swing.JTextField searchTextField;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JMenuItem updateCatalogMenuItem;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog addFileBox;
    private JDialog connectBox;
    private JDialog searchFileBox;
    //private JDialog fileChooserBox;

}
